<template>
    <h1>添加轮播图页面</h1>
    <el-form :model="form" label-width="120px">
        <el-form-item label="图片连接信息">
            <el-input v-model="form.link" />
        </el-form-item>
        <el-form-item label="图片提示信息">
            <el-input v-model="form.alt" />
        </el-form-item>
        <el-form-item label="选择图片">
            <el-upload 
                :http-request="httpRequest"
                class="avatar-uploader" 
                :show-file-list="false" 
            >
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                    <Plus />
                </el-icon>
            </el-upload>
        </el-form-item>
    </el-form>
    <el-button @click="fileUpdate">上传图片</el-button>
</template>

<script>
import { Plus } from '@element-plus/icons-vue'
import { addBanner } from "@/api/banner"
import { ElMessage } from "element-plus"
export default {
    data() {
        return {
            form: {
                link: '',
                alt: '',
                img: ''
            },
            imageUrl: ''
        }
    },
    methods: {
        async fileUpdate() {
            const res = await addBanner(this.form)

            if(res.code !== '200') {
                return ElMessage({
                    type: "warning",
                    message: res.message,
                });
            }

            ElMessage({
                type: "success",
                message: res.message,
            });

            this.form = {
                link: '',
                alt: '',
                img: ''
            }

            this.imageUrl = ""
        }, 

        httpRequest(options) {
            //创建一个文件加载器, 一会用于将我们的 图片信息转换格式
            const reader = new FileReader()

            //指定需要加载的文件
            reader.readAsDataURL(options.file)

            const that = this

            //加载文件需要一定的时间才能执行完毕, 所以我们需要书写一个 监听加载完毕 的事件

            reader.onload = function () {
                // 当前函数执行的时候, 文件已经被处理完毕了
                that.form.img = reader.result

                that.imageUrl = reader.result
            }
        }
    },
    components: {
        Plus,
    }
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.el-input {
    width: 500px;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>